package com.zzy.mccjt.core.interceptor;

import com.zzy.mccjt.annotation.PreAuth;
import com.zzy.mccjt.exception.UnauthorizedException;
import com.zzy.mccjt.model.CurrentOriginSystem;
import com.zzy.mccjt.model.CurrentUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.zzy.mccjt.constant.RequestConstant.B_USER_FLAG;
import static com.zzy.mccjt.constant.RequestConstant.CURRENT_USER;
import static com.zzy.mccjt.constant.RequestConstant.ORIGIN_SYSTEM;
import static com.zzy.mccjt.constant.RequestConstant.USER_FLAG;

/**
 * @program: mccjt-cloud
 * @description:
 * @author: zhouyang.zheng
 * @create: 2022-08-02 17:41
 **/
@Slf4j
public class BRequestInterceptor extends AbstractRequestInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        handleOriginSystem(request);

        if (isNoAuth(request, (HandlerMethod) handler)) {
            handleTenantInfo(request, (HandlerMethod) handler);
            return true;
        }

        String userId = request.getHeader(CURRENT_USER);
        String userFlag = request.getHeader(USER_FLAG);
        if (!isHave((HandlerMethod) handler, PreAuth.class) //B端接口如果非noAuth，必须有preAuth，防止漏掉
                || StringUtils.isEmpty(userId)
                || (Integer.parseInt(userFlag) != B_USER_FLAG)) {
            throw new UnauthorizedException(HttpStatus.UNAUTHORIZED.value(), "UNAUTHORIZED");
        }

        handleTenantInfo(request, (HandlerMethod) handler);

        CurrentUser.set(B_USER_FLAG, Long.parseLong(userId));
        return true;
    }

    private void handleOriginSystem(HttpServletRequest request) {
        // 获取请求来源
        String originSystem = request.getHeader(ORIGIN_SYSTEM);
        if (!StringUtils.isEmpty(originSystem)) {
            CurrentOriginSystem.set(originSystem);
        }
    }
}
